import 'dart:convert';
import '../../lib_baseview/utils/cache_util.dart';
import '../../lib_runtime/event_center.dart';
import '../../lib_runtime/event_constant.dart';
import '../../lib_runtime/logger.dart';
import '../model/login_args.dart';

// 缓存KEY
final LOGINCACHEKEY = "loginCacheKey";
final NEWUSERINFOKEY = "newUserInfoKey";

class LoginStorage {
  static const tag = "LoginManager";
  var log = RLog.create("LoginManager");

  static final instance = LoginStorage._();
  LoginStorage._();

  clearLoginInfo([String cause = ""]) async {
    log.printLog("call LoginStorage.clearLoginInfo() cause by $cause");
    await saveLoginInfo(LoginArgs(type: LoginType.autoLogin));
  }

  saveLoginInfo(LoginArgs loginArgs) async {
    log.printLog("call LoginStorage.saveLoginInfo ${loginArgs.toString()}");
    try {
      var dicData = {
        "loginType": loginArgs.type.name,
        "userId": loginArgs.userId ?? "",
        "token": loginArgs.token ?? "",
        "refreshToken": loginArgs.refreshToken ?? "",
        "emUser": loginArgs.emUser ?? '',
        "emPwd": loginArgs.emPwd ?? '',
        "loginPlatform": loginArgs.loginPlatform?.name ?? ''
      };
      await CacheUtil.saveObject(LOGINCACHEKEY, dicData);
      log.printLog("call LoginStorage.saveLoginInfo success");
      if (loginArgs.userId != null && loginArgs.userId!.isNotEmpty) {
        eventCenter.emit(Event(EventConstant.login, data: loginArgs));
      }
    } catch (e, _) {
      log.printLog("call LoginStorage.saveLoginInfo fail: $e");
    }
  }

  readCurrLoginInfo() async {
    try {
      var dataDic = await CacheUtil.getObject(LOGINCACHEKEY);
      var loginType = dataDic["loginType"];
      var realLoginType = LoginType.values.firstWhere(
          (element) => element.name == loginType,
          orElse: () => LoginType.autoLogin);

      var userId = dataDic["userId"];
      var token = dataDic["token"];
      var refreshToken = dataDic["refreshToken"];
      var emUser = dataDic["emUser"];
      var emPwd = dataDic["emPwd"];
      return LoginArgs(
          type: realLoginType,
          userId: userId,
          token: token,
          emUser: emUser,
          emPwd: emPwd,
          refreshToken: refreshToken);
    } catch (e, _) {
      log.printLog("call LoginStorage.readCurrLoginInfo fail error = $e");
    }
    return null;
  }

  saveNewUserInfoKey(String newUserInfoKey) async {
    try {
      await CacheUtil.saveObject(
          NEWUSERINFOKEY, newUserInfoKey.isEmpty ? "" : newUserInfoKey);
    } catch (e, _) {
      log.printLog("call LoginStorage.saveNewUserInfoKey fail error = $e");
    }
  }

  Future<String?> readUserInfoKey() async {
    try {
      var userInfoKey = await CacheUtil.getObject(NEWUSERINFOKEY);
      log.printLog("call LoginStorage.readUserInfoKey $userInfoKey");
      return userInfoKey;
    } catch (e, _) {
      log.printLog("call LoginStorage.readUserInfoKey fail error = $e");
      return '';
    }
  }
}
